package cn.com.czpb.client.module.news.adapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.custorm.RecycleViewDivider;
import cn.com.czpb.client.model.news.ComResultBean;
import cn.com.czpb.client.model.news.ComResultEntity;
import cn.com.czpb.client.model.news.CommBean;
import cn.com.czpb.client.model.usercenter.EmptyEntity;
import cn.com.czpb.client.module.news.activity.CommentActivity;
import cn.com.czpb.client.module.news.dialog.CommPop;
import cn.com.czpb.client.module.personal.acticity.LevelActivity;
import cn.com.czpb.client.module.personal.acticity.PersonPageActivity;
import cn.com.czpb.client.module.subscribe.activity.SubscribeDetailActivity2;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.AAnim;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.SPUtil;
import cn.com.czpb.client.utils.TUtils;
import cn.com.czpb.client.utils.TextUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.listeners.OnSingleWheelListener;
import cn.addapp.pickers.picker.SinglePicker;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/8/14.
 */

public class NewsCommentAdapter extends BaseMultiItemQuickAdapter<CommBean, BaseViewHolder>{
    private SPUtil spu;
    private NewsCommentRvAdapter adapter;
    private List<CommBean.ChildrenEntity> list;
    private String nid;
    private String cid;
    private String type;
    private Context context;
    private TextView textView;


    /**
     * Same as QuickAdapter#QuickAdapter(Context,int) but with
     * some initialization data.
     *
     * @param data A new list is created out of this one to avoid mutable list
     */
    public NewsCommentAdapter(List<CommBean> data, String nid, String type, Context context) {
        super(data);
        spu = SPUtil.getInstance();
        this.nid = nid;
        this.type = type;
        this.context = context;
        list = new ArrayList<>();
        addItemType(0, R.layout.item_newscomm);
    }

    @Override
    protected void convert(final BaseViewHolder helper, final CommBean item) {
        if (item.getMediatype().equals("1")) {
            helper.getView(R.id.vip).setVisibility(View.VISIBLE);
        }
        switch (helper.getItemViewType()) {
            case 0:
                Glide.with(mContext).load(item.getAvatar_path()).into((ImageView) helper.getView(R.id.iv_user_comm));
                helper.setText(R.id.tv_name_comm, TextUtils.getLengthText(item.getNickname(), 8));
                helper.setText(R.id.tv_lv_comm, item.getUlevel() + " ");
                helper.setText(R.id.tv_content_comm, item.getContent());
                helper.setText(R.id.tv_time_comm, item.getDateline());
                helper.setText(R.id.tv_dianzan_comm, item.getPraise());

                final ImageView iv_Praise = helper.getView(R.id.iv_dianzan);
                final TextView tv_Praise = helper.getView(R.id.tv_dianzan_comm);
                if (item.getIspraise() != null) {
                    if (item.getIspraise().equals("0")) {
                        tv_Praise.setTextColor(mContext.getResources().getColor(R.color.color_999999));
                        iv_Praise.setImageResource(R.drawable.dianzan);
                    } else {
                        tv_Praise.setTextColor(mContext.getResources().getColor(R.color.color_df3031));
                        iv_Praise.setImageResource(R.drawable.dianzan_selected);
                    }
                }
                helper.setNestView(R.id.item_comm);
                RecyclerView recyclerView = helper.getView(R.id.recycler_item_comm);
                adapter = new NewsCommentRvAdapter(list, nid, type, context, helper.getLayoutPosition());
                list.clear();
                list.addAll(item.getChildren());
                if (list == null) {
                    recyclerView.setVisibility(View.GONE);
                }
                setListData(list);
                int height = (int) mContext.getResources().getDimension(R.dimen.x2);
                recyclerView.addItemDecoration(new RecycleViewDivider(mContext,
                        LinearLayoutManager.HORIZONTAL, height,
                        mContext.getResources().getColor(R.color.color_d9d9d9)));
                recyclerView.setLayoutManager(new LinearLayoutManager(helper.itemView.getContext(), LinearLayoutManager.VERTICAL, false));
                recyclerView.setAdapter(adapter);
                helper.addOnClickListener(R.id.tv_content_comm);
                helper.getView(R.id.tv_content_comm).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.putExtra("cid", item.getCid());
                        intent.putExtra("username", item.getNickname());
                        intent.setAction(CommentActivity.SEND_MSG);
                        mContext.sendBroadcast(intent);
                    }
                });
                helper.getView(R.id.ll_dianzan).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if ("0".equals(item.getIspraise())) {
                            Priase(item.getCid(), tv_Praise, iv_Praise);
                        } else {
                            TUtils.toast("您已点赞");
                        }
                    }
                });
                helper.getView(R.id.ll_user).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        if ("1".equals(item.getMediatype())) {
                            intent.putExtra("focusUid", item.getUid());
                            intent.setClass(context, SubscribeDetailActivity2.class);
                        } else {
                            intent.putExtra("uid", item.getUid());
                            intent.setClass(context, PersonPageActivity.class);
                        }
                        mContext.startActivity(intent);
                        AAnim.ActivityStartAnimation((Activity) context);
                    }
                });
                helper.getView(R.id.tv_lv_comm).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(context, LevelActivity.class);
                        intent.putExtra("uid", item.getUid());
                        mContext.startActivity(intent);
                        AAnim.ActivityStartAnimation((Activity) context);
                    }
                });
                final TextView tv = helper.getView(R.id.tv_content_comm);
                helper.getView(R.id.tv_content_comm).setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {

                        tv.setBackgroundColor(mContext.getResources().getColor(R.color.color_d4d4d4));
                        final String msg = tv.getText().toString();
                        CommPop cp = new CommPop((Activity) context, tv, new CommPop.OnClickListeners() {
                            @Override
                            public void OnClicked(View view) {
                                switch (view.getId()) {
                                    case R.id.tv_copy:
                                        ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                                        cmb.setText(msg);
                                        TUtils.toast("已复制");

                                        break;
                                    case R.id.tv_report:
//                                        ClipboardManager cmb1 = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
//                                        cmb1.setText(msg);
                                        SinglePicker picker = ShowReport();
                                        picker.setOnItemPickListener(new OnItemPickListener<String>() {
                                            @Override
                                            public void onItemPicked(int index, String item1) {
                                                ReportUser(item.getUid(), msg, index + "");

                                            }
                                        });
                                        picker.show();
                                        break;
                                }
                            }
                        });
                        cp.showAsPullUp(tv, 0, 0);

                        return true;
                    }

                });

                break;
        }
    }


    public void setListData(List<CommBean.ChildrenEntity> list) {

        adapter.setNewData(list);
        adapter.notifyDataSetChanged();

    }

//    @Override
//    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//
//    }

//    @Override
//    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//        CommBean.ChildrenEntity item1 = (CommBean.ChildrenEntity) adapter.getItem(position);
////        ReplyDialog dialog = new ReplyDialog(mContext, R.style.ChangeNamedialog, item1);
////        dialog.show();
//        Intent intent = new Intent();
//        if (item1 != null) {
//            Toast.makeText(context, "嵌套RecycleView item 收到  :"+item1.getNickname()+ " 一次", Toast.LENGTH_SHORT).show();
//            intent.putExtra("cid", item1.getCid());
//            intent.putExtra("username", item1.getNickname());
//            intent.setAction(CommentActivity.SEND_MSG);
//        }
//        mContext.sendBroadcast(intent);
//    }

    class ReplyDialog extends Dialog implements View.OnClickListener {
        EditText et_reply;
        TextView tv_send;
        CommBean.ChildrenEntity item;

        public ReplyDialog(Context context) {
            super(context);
            init();
        }

        public ReplyDialog(@NonNull Context context, @StyleRes int themeResId, CommBean.ChildrenEntity item) {
            super(context, themeResId);
            init();
            this.item = item;
        }

        private void init() {
            WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
            int width = wm.getDefaultDisplay().getWidth();
            View view = LayoutInflater.from(mContext).inflate(R.layout.et_reply_laout, null);
            setContentView(view);
            et_reply = view.findViewById(R.id.et_reply);
            tv_send = view.findViewById(R.id.tv_send);
            tv_send.setOnClickListener(this);
            Window dialogWindow = getWindow();
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            dialogWindow.setGravity(Gravity.END | Gravity.BOTTOM);
            lp.width = width;
            dialogWindow.setAttributes(lp);
        }

        @Override
        public void onClick(View view) {
            String msg = et_reply.getText().toString().trim();
            if (spu.getUser() == null) {
                PageCtrl.start2LoginActivity((Activity) mContext);
            } else {
                if (msg == null) {
                    TUtils.toast("请输入内容");
                } else {
                    LogUtils.e("cid----" + item.getUid());
//                    sendComment(msg, item.getCid());
                }
            }
        }

        private void sendComment(String content, String cid) {

            Map<String, String> map = new HashMap<>();
            map.put("nid", nid);
            map.put("uid", spu.getUser().getUid());
            map.put("type", type);
            map.put("title", nid);
            map.put("content", content);
            map.put("cid", cid);
            map.put("json_url", "fsdfsdfsfs");//随便传一个
            map.put("siteid", InterfaceJsonfile.SITEID);
            Factory.provideHttpService()
                    .newsComment(ParamUtils.getRequestParam(map))
                    .onBackpressureBuffer()
                    .subscribeOn(Schedulers.io())
                    .filter(new Func1<ComResultEntity, Boolean>() {
                        @Override
                        public Boolean call(ComResultEntity entity) {
                            LogUtils.i("200-->" + entity.code);
                            if ("200".equals(entity.code)) {
                                LogUtils.i("200-->成功");
                                return true;
                            }
                            LogUtils.i("200失败");
                            return false;
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<ComResultEntity>() {
                        @Override
                        public void call(ComResultEntity entity) {

                            if ("200".equals(entity.code)) {
                                TUtils.toast("评论成功");
                                et_reply.setText("");
                            } else {
                                TUtils.toast(entity.msg);
                            }
//                            setData();
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            TUtils.toast("评论失败");

                        }
                    });
        }

    }

    public void Priase(String cid, final TextView tv, final ImageView iv) {
        final ComResultBean[] obj = {new ComResultBean()};
        Map<String, String> map = new HashMap<>();
        map.put("uid", spu.getUser().getUid());
        map.put("device", DeviceUtils.getMyUUID(mContext));
        map.put("cid", cid);
        map.put("siteid", InterfaceJsonfile.SITEID);

        Factory.provideHttpService().PraiseOnComment(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<ComResultEntity, Boolean>() {
                    @Override
                    public Boolean call(ComResultEntity emptyEntity) {
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ComResultEntity>() {
                    @Override
                    public void call(ComResultEntity emptyEntity) {

                        LogUtils.e("code---" + emptyEntity.code);
                        if (emptyEntity.code.equals("200")) {
                            tv.setText(emptyEntity.data.getPraisenum());
                            tv.setTextColor(mContext.getResources().getColor(R.color.color_df3031));
                            iv.setImageResource(R.drawable.dianzan_selected);
                        } else {
                            TUtils.toast(emptyEntity.msg);
                        }
                    }
                });

    }

    public SinglePicker ShowReport() {
        int ts = (int) context.getResources().getDimension(R.dimen.x32);
        int w = (int) context.getResources().getDimension(R.dimen.x84);
        ArrayList<String> list = new ArrayList<>();
        list.add("淫秽色情");
        list.add("营销广告");
        list.add("恶意攻击谩骂");
        list.add("其他");
//        String[] ss = (String[]) list.toArray();
        final SinglePicker<String> picker = new SinglePicker<>((Activity) context, list);
        picker.setCanLoop(false);//不禁用循环
        picker.setLineVisible(true);
        picker.setShadowVisible(true);
        picker.setTitleText("举报理由");
        picker.setTopHeight(50);//顶部标题栏高度
        picker.setTopLineColor(context.getResources().getColor(R.color.color_dddddd));//顶部标题栏下划线颜色
        picker.setTopLineHeight(1);//顶部标题栏下划线高度
        picker.setTitleTextColor(context.getResources().getColor(R.color.color_333333));
        picker.setCancelTextColor(context.getResources().getColor(R.color.color_108ee9));//顶部取消按钮文字颜色
        picker.setCancelTextSize(14);
        picker.setSubmitTextColor(context.getResources().getColor(R.color.color_108ee9));//顶部确定按钮文字颜色
        picker.setSubmitTextSize(14);
        picker.setTitleTextSize(14);
        picker.setTextSize(14);
        picker.setSelectedIndex(1);
        picker.setWheelModeEnable(true);
        //启用权重 setWeightWidth 才起作用
//        picker.setLabel("分");
        picker.setWeightEnable(true);
        picker.setWeightWidth(1);
        picker.setSelectedTextColor(context.getResources().getColor(R.color.color_333333));//前四位值是透明度
        picker.setUnSelectedTextColor(context.getResources().getColor(R.color.color_a9a9a9));
        picker.setOnSingleWheelListener(new OnSingleWheelListener() {
            @Override
            public void onWheeled(int index, String item) {

            }
        });

        return picker;
    }

    private void ReportUser(String uid, String content, String type) {

        Map<String, String> map = new HashMap<>();

        map.put("uid", uid);

//        map.put("content", content);
        map.put("optionsRadios", type);
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .reportUser(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<EmptyEntity, Boolean>() {
                    @Override
                    public Boolean call(EmptyEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<EmptyEntity>() {
                    @Override
                    public void call(EmptyEntity entity) {

                        if ("200".equals(entity.code)) {
                            TUtils.toast(entity.msg);

                        } else {
                            TUtils.toast(entity.msg);
                        }
//
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {


                    }
                });
    }
}
